<template>
  <div class="article-editor-container">
    <el-card class="form-card">
      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          label-position="top"
          @submit.prevent="handleSubmit"
      >
        <!-- 标题 -->
        <el-form-item label="文章标题" prop="title">
          <el-input
              v-model="form.title"
              placeholder="请输入文章标题"
              clearable
          />
        </el-form-item>

        <!-- 类型选择 -->
        <el-form-item label="文章类型" prop="type">
          <el-select
              v-model="form.type"
              placeholder="请选择文章类型"
              class="full-width"
              clearable
          >
            <el-option
                v-for="item in articleTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 封面上传 -->
        <el-form-item label="封面图片" prop="img">
          <el-upload
              v-loading="uploadLoading"
              class="cover-uploader"
              :http-request="handleUpload"
              :show-file-list="false"
              accept="image/png, image/jpeg"
          >
            <template #trigger>
              <div class="uploader-content">
                <img
                    v-if="form.img"
                    :src="form.img"
                    class="cover-image"
                    alt="文章封面"
                />
                <div v-else class="upload-placeholder">
                  <el-icon :size="40"><Plus /></el-icon>
                  <div class="upload-tip">点击上传封面图片</div>
                </div>
              </div>
            </template>
          </el-upload>
          <div v-if="uploadLoading" class="upload-progress">
            <el-progress
                :percentage="uploadPercent"
                :stroke-width="16"
                status="success"
                striped
            />
            <div class="progress-tip">上传中，请勿关闭页面...</div>
          </div>
        </el-form-item>

        <!-- 正文编辑器 -->
        <el-form-item label="文章正文" prop="text">
          <Tinymce
              v-model="form.text"
              :height="410"
              placeholder="请输入文章内容..."
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              size="large"
              :loading="submitting"
              native-type="submit"
              class="submit-btn"
          >
            {{ isEditMode ? '更新文章' : '发布文章' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Tinymce from '@/components/Tinymce/Tinymce.vue'
import {getDict} from "@/api/common.js";
import {addArticle, getArticleById, uploadAvatar} from "@/api/articleApi.js";

// 响应式状态
const formRef = ref(null)
const form = reactive({
  id: null,
  title: '',
  type: '',
  img: '',
  text: ''
})
const articleTypes = ref([])
const uploadPercent = ref(0)
const uploadLoading = ref(false)
const submitting = ref(false)
const isEditMode = ref(false)
// 路由
const router = useRouter()
const route = useRoute()
// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 30, message: '标题长度在5-30个字符之间', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择文章类型', trigger: 'change' }],
  img: [{ required: true, message: '请上传封面图片', trigger: 'change' }],
  text: [
    { required: true, message: '请输入文章正文', trigger: 'blur' },
    { max: 10000, message: '正文内容最多10000字', trigger: 'blur' }
  ]
})

// 初始化数据
onMounted(async () => {
  await fetchArticleTypes()
  await checkEditMode()
})

// 获取文章类型字典
const fetchArticleTypes = async () => {
  try {
    const res = await getDict({ value: 'wz_lx' })
    articleTypes.value = res.data[0].child
  } catch (error) {
    ElMessage.error('获取文章类型失败')
  }
}

// 检查是否为编辑模式
const checkEditMode = async () => {
  console.log(router)
  const articleId = route.query.id
  // console.log(articleId)
  if (!articleId) return

  try {
    const res = await getArticleById(articleId)
    Object.assign(form, {
      id: res.data.id,
      title: res.data.title,
      type: res.data.articleType,
      img: res.data.pic,
      text: res.data.articleMx.text
    })
    isEditMode.value = true
  } catch (error) {
    ElMessage.error('获取文章信息失败')
  }
}



const handleSubmit = async () => {
  try {
    submitting.value = true
    await formRef.value.validate()

    await addArticle(form)
    ElMessage.success(isEditMode.value ? '更新成功' : '发布成功')
    await router.push({name: 'MyArticles'})
  } catch (error) {
    if (!error) return // 验证未通过时不提示
    ElMessage.error(error.message || '操作失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 处理图片上传
const handleUpload = async ({ file }) => {
  try {
    uploadLoading.value = true
    uploadPercent.value = 0

    const formData = new FormData()
    formData.append('file', file)

    const onUploadProgress = e => {
      uploadPercent.value = Math.round((e.loaded * 100) / e.total)
    }

    const res = await uploadAvatar(formData, onUploadProgress)
    form.img = `/img/system/download?fileName=${res.data}`
    ElMessage.success('封面图片上传成功')
  } catch (error) {
    ElMessage.error('图片上传失败：' + (error.message || '文件大小可能超过限制'))
  } finally {
    uploadLoading.value = false
    uploadPercent.value = 0
  }
}
</script>

<style scoped>
.form-card {
  height: calc(100vh - 69px);
  overflow-y: auto;
}

.full-width {
  width: 100%;
}

.cover-uploader {
  border: 2px dashed var(--el-border-color);
  border-radius: 8px;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: var(--el-color-primary);
}

.uploader-content {
  width: 100%;
  height: 140px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.cover-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 6px;
  object-fit: cover;
}

.upload-placeholder {
  text-align: center;
  color: var(--el-text-color-secondary);
}

.upload-tip {
  margin-top: 8px;
  font-size: 14px;
}

.upload-progress {
  margin-top: 16px;
}

.progress-tip {
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.submit-btn {
  width: 240px;
  font-weight: 500;
  letter-spacing: 1px;
}

@media (max-width: 768px) {
  .article-editor-container {
    padding: 0;
    margin: 16px;
  }

  .form-card {
    border-radius: 0;
    box-shadow: none;
  }
}
</style>